package com.sjz.bookmark.tree;

import cn.hutool.core.bean.BeanUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowFactory;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.ui.treeStructure.Tree;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import com.sjz.bookmark.mysql.BookmarkRecord;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;



public class SjzBookmarkTree implements ToolWindowFactory {


    @Override
    public void createToolWindowContent(@NotNull Project project, @NotNull ToolWindow toolWindow) {
        // 初始化 BookmarkNode 数组
        BookmarkRecord rootNode = new BookmarkRecord();
        // 创建树模型
        DefaultTreeModel treeModel = new DefaultTreeModel(new DefaultMutableTreeNode(rootNode));
        Tree tree = new Tree(treeModel);
        // 设置树可拖拽
        tree.setDragEnabled(true);
        tree.setDropMode(DropMode.ON_OR_INSERT);
        // 设置树可编辑
        tree.setEditable(false);
        // 设置树的可视化属性
        tree.setShowsRootHandles(true);
        tree.setRootVisible(true);
        tree.setExpandsSelectedPaths(true);
        tree.setBackground(UIUtil.getTreeBackground());
        tree.setFont(JBUI.Fonts.smallFont());
        // 设置自定义渲染器
        tree.setCellRenderer(new BookmarkTreeCellRenderer());

        // 添加展开和关闭监听器
        tree.addTreeExpansionListener(new TreeExpansionListener() {
            @Override
            public void treeExpanded(TreeExpansionEvent event) {
                BookmarkRecord node = (BookmarkRecord) event.getPath().getLastPathComponent();
                BookmarkRecord bean = BeanUtil.toBean(node, BookmarkRecord.class);
            }

            @Override
            public void treeCollapsed(TreeExpansionEvent event) {
                BookmarkRecord node = (BookmarkRecord) event.getPath().getLastPathComponent();
                BookmarkRecord bean = BeanUtil.toBean(node, BookmarkRecord.class);
            }
        });

        // 添加鼠标事件监听器
        tree.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                BookmarkRecord lastSelectedPathComponent = (BookmarkRecord) tree.getLastSelectedPathComponent();

            }

//            @Override
//            public void mouseClicked(MouseEvent e) {
//                // 处理双击事件
//                if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2) {
//                    // 执行双击事件逻辑
//                    System.out.println("双击");
//                }
//            }
//        });

//        // 添加选择监听器
//        tree.addTreeSelectionListener(e -> {
//            TreePath path = e.getNewLeadSelectionPath();
//            if (path != null) {
//                System.out.println("888888888888888888888888");
//                // 处理节点选择逻辑
//            }
//        });

//        // 可选：添加双击事件监听
//        tree.addMouseListener(new MouseAdapter() {
//            @Override
//            public void mouseClicked(MouseEvent e) {
//                if (e.getClickCount() == 2 && SwingUtilities.isLeftMouseButton(e)) {
//
//                }
//            }
//        });

//        // 添加模型监听器
//        treeModel.addTreeModelListener(new TreeModelListener() {
//            @Override
//            public void treeNodesChanged(TreeModelEvent e) {
//                System.out.println("节点变化");
//            }
//
//            @Override
//            public void treeNodesInserted(TreeModelEvent e) {
//                System.out.println("节点插入");
//                // 处理节点插入事件
//            }
//
//            @Override
//            public void treeNodesRemoved(TreeModelEvent e) {
//                System.out.println("节点删除");
//                // 处理节点删除事件
//            }
//
//            @Override
//            public void treeStructureChanged(TreeModelEvent e) {
//                System.out.println("树结构变化");
//                // 处理树结构变化事件
//            }
        });

        // 创建滚动面板并添加到工具窗口
        JPanel panel = new JPanel(new BorderLayout());
        JBScrollPane scrollPane = new JBScrollPane(tree);
        scrollPane.setBorder(JBUI.Borders.empty(1)); // IDE 风格的边距
        panel.add(scrollPane, BorderLayout.CENTER);
        // 添加刷新按钮
        JButton refreshButton = new JButton("刷新");
        refreshButton.addActionListener(e -> {

        });
        panel.add(refreshButton, BorderLayout.SOUTH);
        toolWindow.getComponent().add(panel);
    }


    /**
     * 递归查找目标节点
     *
     * @param parentNode 父节点
     * @param userObject 目标节点的用户对象（例如 BookmarkRecord）
     * @return 目标节点，如果未找到则返回 null
     */
    private static DefaultMutableTreeNode findNodeByUserObject(DefaultMutableTreeNode parentNode, Object userObject) {
        // 检查当前节点是否为目标节点
        if (parentNode.getUserObject().toString().equals(userObject.toString())) {
            return parentNode;
        }
        // 递归查找子节点
        for (int i = 0; i < parentNode.getChildCount(); i++) {
            DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) parentNode.getChildAt(i);
            DefaultMutableTreeNode result = findNodeByUserObject(childNode, userObject);
            if (result != null) {
                return result;
            }
        }
        return null; // 未找到目标节点
    }

    private Tree initTree(Project project) {
        // 初始化 BookmarkNode 数组
        // 创建树模型
        DefaultTreeModel treeModel = new DefaultTreeModel(new DefaultMutableTreeNode(new BookmarkRecord()));
        Tree tree = new Tree(treeModel);
        // 设置树可拖拽
        tree.setDragEnabled(true);
        tree.setDropMode(DropMode.ON_OR_INSERT);
        // 设置树可编辑
        tree.setEditable(false);
        // 设置树的可视化属性
        tree.setShowsRootHandles(true);
        tree.setRootVisible(true);
        tree.setExpandsSelectedPaths(true);
        tree.setBackground(UIUtil.getTreeBackground());
        tree.setFont(JBUI.Fonts.smallFont());
        // 设置自定义渲染器
        tree.setCellRenderer(new BookmarkTreeCellRenderer());

        // 添加展开和关闭监听器
        tree.addTreeExpansionListener(new TreeExpansionListener() {
            @Override
            public void treeExpanded(TreeExpansionEvent event) {
                BookmarkRecord node = (BookmarkRecord) event.getPath().getLastPathComponent();
                BookmarkRecord bean = BeanUtil.toBean(node, BookmarkRecord.class);
            }

            @Override
            public void treeCollapsed(TreeExpansionEvent event) {
                BookmarkRecord node = (BookmarkRecord) event.getPath().getLastPathComponent();
                BookmarkRecord bean = BeanUtil.toBean(node, BookmarkRecord.class);
            }
        });

        // 添加鼠标事件监听器
        tree.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e){}

            BookmarkRecord lastSelectedPathComponent = (BookmarkRecord) tree.getLastSelectedPathComponent();

        });
        return tree;
    }
}

//            @Override
//            public void mouseClicked(MouseEvent e) {
//                // 处理双击事件
//                if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2) {
//                    // 执行双击事件逻辑
//                    System.out.println("双击");
//                }
//            }
//        });

//        // 添加选择监听器
//        tree.addTreeSelectionListener(e -> {
//            TreePath path = e.getNewLeadSelectionPath();
//            if (path != null) {
//                System.out.println("888888888888888888888888");
//                // 处理节点选择逻辑
//            }
//        });

//        // 可选：添加双击事件监听
//        tree.addMouseListener(new MouseAdapter() {
//            @Override
//            public void mouseClicked(MouseEvent e) {
//                if (e.getClickCount() == 2 && SwingUtilities.isLeftMouseButton(e)) {
//
//                }
//            }
//        });

//        // 添加模型监听器
//        treeModel.addTreeModelListener(new TreeModelListener() {
//            @Override
//            public void treeNodesChanged(TreeModelEvent e) {
//                System.out.println("节点变化");
//            }
//
//            @Override
//            public void treeNodesInserted(TreeModelEvent e) {
//                System.out.println("节点插入");
//                // 处理节点插入事件
//            }
//
//            @Override
//            public void treeNodesRemoved(TreeModelEvent e) {
//                System.out.println("节点删除");
//                // 处理节点删除事件
//            }
//
//            @Override
//            public void treeStructureChanged(TreeModelEvent e) {
//                System.out.println("树结构变化");
//                // 处理树结构变化事件
//            }
